define([
    'angular',
    'angular-ngTable'
], function(angular) {
    var factory = angular.module('app.factory.table', ['ngTable']);
    
    // ngTable
    factory.factory('Table', ['$q', '$window', 'NgTableParams', function($q, $window, NgTableParams) {
        var tableFactory = {
            $create: function(settings, options) {
                var _settings = angular.extend({
                    showPage: true
                }, settings);
                var _options = angular.extend({
                    filterDelay: 200
                }, options);

                if (_settings['pageable']) {
                    _settings = angular.extend({
                        page: 1,
                        count: 10,
                        total: 0
                    }, _settings);
                    _options = angular.extend({
                        paginationMinBlocks: 3,
                        paginationMaxBlocks: 10,
                        counts: [10, 25, 50, 100],
                        getData: function(params) {
                            params['offset'] = (params.page() - 1) * params.count();
                            params['limit'] = params.count();

                            var defer = $q.defer();
                            _options['getPageData'](params).then(function(data) {
                                if (data == null || data.length == 0) {
                                    if (params.page() > 1) {
                                        params.page(params.page() - 1);

                                        options['getPageData'](params).then(function(response) {
                                            defer.resolve(response);
                                        }, function(response) {
                                            defer.reject(response);
                                        });
                                    } else {
                                        defer.resolve(data);
                                    }
                                } else {
                                    defer.resolve(data);
                                }
                            }, function(data) {
                                defer.reject(data);
                            });

                            return defer.promise;
                        }
                    }, _options);
                }

                return new NgTableParams(_settings, _options);
            }
        };

        return tableFactory;
    }]);

    return factory;
});